package com.supor.aiot.mine.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.KeyEvent;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.config.HttpConstant;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.data.AppDelegate;
import com.android.baseconfig.data.http.AppNetDelegate;
import com.cmic.sso.sdk.auth.AuthnHelper;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.helper.ConfigActivityManager;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.WsHelper;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.databinding.ActivityDebugSettingBinding;


public class DebugSettingActivity extends BaseConfigActivity<NoViewModel, ActivityDebugSettingBinding> {

    boolean debugMode = false;
    int currentServer = 0;
    boolean selectDebugMode = false;
    int selectServer = 0;
    boolean isSwitch = false;

    @Override
    protected int resourceId() {
        return R.layout.activity_debug_setting;
    }

    protected void initData() {
        bindingView.toolbar.setIvLeftOnClickListener(v -> {
            if (isSwitch) {
                return;
            }
            finish();
        });

        bindingView.rgH5DebugMode.check(AppAgent.h5Debug ? R.id.rb_h5_open : R.id.rb_h5_close);

        selectDebugMode = debugMode = BaseSharedPreferences.getBoolean(this,
                Constants.Key.param_debug_mode, false);
        if (debugMode) {
            bindingView.rgDebugMode.check(R.id.rb_open);
        } else {
            bindingView.rgDebugMode.check(R.id.rb_close);
        }

        bindingView.rgH5DebugMode.setOnCheckedChangeListener((group, checkedId) ->
                AppAgent.h5Debug = (checkedId == R.id.rb_h5_open));

        bindingView.rgDebugMode.setOnCheckedChangeListener((group, checkedId) -> selectDebugMode =
                checkedId == R.id.rb_open);

        selectServer = currentServer = BaseSharedPreferences.getInt(this,
                Constants.Key.param_server);
        Logc.i("currentServer= " + selectServer);
        if (currentServer == 0) {
            bindingView.rgNetwork.check(R.id.rb_release);
        } else if (currentServer == 1) {
            bindingView.rgNetwork.check(R.id.rb_pre);
        } else if (currentServer == 2) {
            bindingView.rgNetwork.check(R.id.rb_test);
        }

        bindingView.rgNetwork.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_release) {
                selectServer = 0;
            } else if (checkedId == R.id.rb_pre) {
                selectServer = 1;
            } else if (checkedId == R.id.rb_test) {
                selectServer = 2;
            }
        });
        bindingView.btnSave.setOnClickListener(v -> onViewClicked());
    }

    public void onViewClicked() {
        if (isSwitch) {
            return;
        }
        if (debugMode == selectDebugMode && currentServer == selectServer) {
            ToastUtils.getInstance().showCustomToast("当前模式和环境未改变");
            return;
        }
        ToastUtils.getInstance().showCustomToast("正在切换环境，App将在3s后重启");
        isSwitch = true;
        SuporPresenter.getInstance().reportCloseAccount(2);
        BaseSharedPreferences.setString(this, Constants.Key.param_saveInfo, "");
        BaseSharedPreferences.setString(this, Constants.Key.USER_INFO, "");
        BaseSharedPreferences.setString(this, HttpConstant.TOKEN, "");
        BaseSharedPreferences.setBoolean(this, Constants.Key.param_debug_mode, selectDebugMode);
        BaseSharedPreferences.setInt(this, Constants.Key.param_server, selectServer);
        BaseSharedPreferences.setLong(this, Constants.Key.USER_PRIVACY_TIME, 0L);
        BaseSharedPreferences.setLong(this, Constants.Key.USER_SERVER_TIME, 0L);
        GlobalDataCache.deviceTree = null;
        GlobalDataCache.productTypeList = null;
        GlobalDataCache.userInfo = null;
        AppAgent.isShowCmcc = false;
        AppAgent.setLogin(false);
        WsHelper.getInstance().exit();

        Logc.i("onViewClicked: server: " + selectServer);
        AppAgent.currentServer = selectServer;
        if (selectServer == 0) {
            AppDelegate.setHost(Constants.APP_RELEASE_URL);
        } else if (selectServer == 1) {
            AppDelegate.setHost(Constants.APP_PRE_URL);
        } else if (selectServer == 2) {
            AppDelegate.setHost(Constants.APP_TEST_URL);
        }
        //初始化基础模块
        AppDelegate.init(AppAgent.getApp());
        RxBus3.getInstance().post("switch_net", true);

        if (SystemUtils.isApkInDebug(this) || selectDebugMode) {
            AuthnHelper.setDebugMode(true);
            AppNetDelegate.setLogger(true);
            Logc.setLogLevel(Logc.LogLevel.LEVEL_VERBOSE);
            com.supor.aiot.websocket.Logc.setLogLevel(com.supor.aiot.websocket.Logc.LogLevel.LEVEL_VERBOSE);
        } else {
            AuthnHelper.setDebugMode(false);
            Logc.setLogLevel(Logc.LogLevel.LEVEL_WARN);
            com.supor.aiot.websocket.Logc.setLogLevel(com.supor.aiot.websocket.Logc.LogLevel.LEVEL_WARN);
        }
        new Handler().postDelayed(() -> {
            // ActivityManager.finishAll();
            finish();
            ConfigActivityManager.finishAll();
            Activity activity = ActivityManager.getActivity(1);
            Logc.d("onViewClicked: activity: " + activity);
            if (activity != null && activity.getClass().getSimpleName().equalsIgnoreCase(
                    "H5Activity")) {
                activity.onKeyDown(4, new KeyEvent(0, 4));
                activity.onBackPressed();
            } else {
                ActivityManager.finishAll();
            }
        }, 2000);
        // new Handler().postDelayed(() -> {
        //     // ActivityManager.finishAll();
        //     ActivityManager.finishAll();
        // }, 2000);
        new Handler().postDelayed(() -> {
            // Intent intent = new Intent(AppAgent.getApp(), SuporMainActivity.class);
            // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // // AppAgent.getApp().startActivity(intent);
            // PendingIntent restartIntent = PendingIntent.getActivity(AppAgent.getApp(),
            //         0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            // //退出程序
            // AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
            // assert mgr != null;
            // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000,
            //         restartIntent); // 1秒钟后重启应用
            //
            // // 退出程序
            // android.os.Process.killProcess(android.os.Process.myPid());
            // System.exit(1);
            Intent LaunchIntent = AppAgent.getApp().getPackageManager()
                    .getLaunchIntentForPackage(AppAgent.getApp().getPackageName());
            if (LaunchIntent != null) {
                LaunchIntent.setPackage(null);
                LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                AppAgent.getApp().startActivity(LaunchIntent);
            }
            Logc.i("LaunchIntent: end");


            // 切换环境后重新获取产品列表
            if (GlobalDataCache.productTypeList == null) {
                GlobalDataCache.getAllProduct();
            }
        }, 3000);
    }
}
